import { ref, onMounted, onUnmounted, type Ref } from 'vue'

// 快捷键定义类型
export interface ShortcutKey {
  id: string
  keys: string[] // 键组合，如 ['ctrl', 'enter']
  description: string
  handler: (event: KeyboardEvent) => void
  disabled?: Ref<boolean>
  global?: boolean // 是否为全局快捷键
}

// 快捷键组合解析
export interface ParsedShortcut {
  ctrl: boolean
  alt: boolean
  shift: boolean
  meta: boolean
  key: string
}

// 快捷键管理器
class ShortcutManager {
  private shortcuts = new Map<string, ShortcutKey>()
  private activeElement: HTMLElement | null = null
  private isListening = false

  constructor() {
    this.handleKeyDown = this.handleKeyDown.bind(this)
  }

  /**
   * 注册快捷键
   */
  register(shortcut: ShortcutKey): void {
    this.shortcuts.set(shortcut.id, shortcut)
  }

  /**
   * 注销快捷键
   */
  unregister(shortcutId: string): void {
    this.shortcuts.delete(shortcutId)
  }

  /**
   * 开始监听快捷键
   */
  startListening(element?: HTMLElement): void {
    if (this.isListening) return

    this.activeElement = element || document.documentElement
    this.activeElement.addEventListener('keydown', this.handleKeyDown, true)
    this.isListening = true
  }

  /**
   * 停止监听快捷键
   */
  stopListening(): void {
    if (!this.isListening || !this.activeElement) return

    this.activeElement.removeEventListener('keydown', this.handleKeyDown, true)
    this.activeElement = null
    this.isListening = false
  }

  /**
   * 解析键盘事件
   */
  private parseKeyEvent(event: KeyboardEvent): ParsedShortcut {
    return {
      ctrl: event.ctrlKey || event.metaKey, // Mac上的Cmd键
      alt: event.altKey,
      shift: event.shiftKey,
      meta: event.metaKey,
      key: event.key.toLowerCase()
    }
  }

  /**
   * 解析快捷键字符串
   */
  private parseShortcutKeys(keys: string[]): ParsedShortcut {
    const result: ParsedShortcut = {
      ctrl: false,
      alt: false,
      shift: false,
      meta: false,
      key: ''
    }

    keys.forEach(key => {
      const lowerKey = key.toLowerCase()
      switch (lowerKey) {
        case 'ctrl':
        case 'control':
          result.ctrl = true
          break
        case 'alt':
          result.alt = true
          break
        case 'shift':
          result.shift = true
          break
        case 'meta':
        case 'cmd':
        case 'command':
          result.meta = true
          break
        default:
          result.key = lowerKey
      }
    })

    return result
  }

  /**
   * 检查快捷键是否匹配
   */
  private isShortcutMatch(eventShortcut: ParsedShortcut, definedShortcut: ParsedShortcut): boolean {
    return (
      eventShortcut.ctrl === definedShortcut.ctrl &&
      eventShortcut.alt === definedShortcut.alt &&
      eventShortcut.shift === definedShortcut.shift &&
      eventShortcut.meta === definedShortcut.meta &&
      eventShortcut.key === definedShortcut.key
    )
  }

  /**
   * 处理键盘事件
   */
  private handleKeyDown(event: KeyboardEvent): void {
    const eventShortcut = this.parseKeyEvent(event)

    for (const [id, shortcut] of this.shortcuts) {
      // 检查是否被禁用
      if (shortcut.disabled?.value) continue

      // 解析定义的快捷键
      const definedShortcut = this.parseShortcutKeys(shortcut.keys)

      // 检查是否匹配
      if (this.isShortcutMatch(eventShortcut, definedShortcut)) {
        event.preventDefault()
        event.stopPropagation()
        
        try {
          shortcut.handler(event)
        } catch (error) {
          console.error(`Error executing shortcut ${id}:`, error)
        }
        
        break // 只执行第一个匹配的快捷键
      }
    }
  }

  /**
   * 获取所有注册的快捷键
   */
  getAllShortcuts(): ShortcutKey[] {
    return Array.from(this.shortcuts.values())
  }

  /**
   * 格式化快捷键显示
   */
  formatShortcut(keys: string[]): string {
    const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
    
    return keys.map(key => {
      const lowerKey = key.toLowerCase()
      switch (lowerKey) {
        case 'ctrl':
        case 'control':
          return isMac ? '⌘' : 'Ctrl'
        case 'alt':
          return isMac ? '⌥' : 'Alt'
        case 'shift':
          return isMac ? '⇧' : 'Shift'
        case 'meta':
        case 'cmd':
        case 'command':
          return '⌘'
        case 'enter':
          return 'Enter'
        case 'escape':
          return 'Esc'
        case 'backspace':
          return 'Backspace'
        case 'delete':
          return 'Del'
        case 'tab':
          return 'Tab'
        case 'space':
          return 'Space'
        case 'arrowup':
          return '↑'
        case 'arrowdown':
          return '↓'
        case 'arrowleft':
          return '←'
        case 'arrowright':
          return '→'
        default:
          return key.toUpperCase()
      }
    }).join(isMac ? '' : '+')
  }
}

// 全局快捷键管理器实例
const globalShortcutManager = new ShortcutManager()

// 组合式API
export const useShortcuts = (element?: Ref<HTMLElement | undefined>) => {
  const shortcuts = ref<ShortcutKey[]>([])

  const registerShortcut = (shortcut: ShortcutKey) => {
    globalShortcutManager.register(shortcut)
    shortcuts.value = globalShortcutManager.getAllShortcuts()
  }

  const unregisterShortcut = (shortcutId: string) => {
    globalShortcutManager.unregister(shortcutId)
    shortcuts.value = globalShortcutManager.getAllShortcuts()
  }

  const formatShortcut = (keys: string[]) => {
    return globalShortcutManager.formatShortcut(keys)
  }

  onMounted(() => {
    globalShortcutManager.startListening(element?.value)
  })

  onUnmounted(() => {
    globalShortcutManager.stopListening()
  })

  return {
    shortcuts,
    registerShortcut,
    unregisterShortcut,
    formatShortcut
  }
}

// 预定义的快捷键
export const createDefaultShortcuts = (handlers: {
  sendMessage?: () => void
  newChat?: () => void
  clearChat?: () => void
  toggleSidebar?: () => void
  focusInput?: () => void
  showHelp?: () => void
  saveChat?: () => void
  openSettings?: () => void
  confirmTask?: () => void
  cancelExecution?: () => void
}) => {
  const shortcuts: ShortcutKey[] = []

  if (handlers.sendMessage) {
    shortcuts.push({
      id: 'send-message',
      keys: ['ctrl', 'enter'],
      description: '发送消息',
      handler: handlers.sendMessage,
      global: true
    })
  }

  if (handlers.newChat) {
    shortcuts.push({
      id: 'new-chat',
      keys: ['ctrl', 'n'],
      description: '新建聊天',
      handler: handlers.newChat,
      global: true
    })
  }

  if (handlers.clearChat) {
    shortcuts.push({
      id: 'clear-chat',
      keys: ['ctrl', 'shift', 'delete'],
      description: '清空聊天',
      handler: handlers.clearChat,
      global: true
    })
  }

  if (handlers.toggleSidebar) {
    shortcuts.push({
      id: 'toggle-sidebar',
      keys: ['ctrl', 'b'],
      description: '切换侧边栏',
      handler: handlers.toggleSidebar,
      global: true
    })
  }

  if (handlers.focusInput) {
    shortcuts.push({
      id: 'focus-input',
      keys: ['ctrl', '/'],
      description: '聚焦输入框',
      handler: handlers.focusInput,
      global: true
    })
  }

  if (handlers.showHelp) {
    shortcuts.push({
      id: 'show-help',
      keys: ['f1'],
      description: '显示帮助',
      handler: handlers.showHelp,
      global: true
    })
  }

  if (handlers.saveChat) {
    shortcuts.push({
      id: 'save-chat',
      keys: ['ctrl', 's'],
      description: '保存聊天记录',
      handler: handlers.saveChat,
      global: true
    })
  }

  if (handlers.openSettings) {
    shortcuts.push({
      id: 'open-settings',
      keys: ['ctrl', ','],
      description: '打开设置',
      handler: handlers.openSettings,
      global: true
    })
  }

  if (handlers.confirmTask) {
    shortcuts.push({
      id: 'confirm-task',
      keys: ['ctrl', 'shift', 'enter'],
      description: '确认任务执行',
      handler: handlers.confirmTask,
      global: true
    })
  }

  if (handlers.cancelExecution) {
    shortcuts.push({
      id: 'cancel-execution',
      keys: ['escape'],
      description: '取消执行',
      handler: handlers.cancelExecution,
      global: true
    })
  }

  return shortcuts
}

export default globalShortcutManager